package top.lyc829.mymusic.ui.custom

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import com.lzx.starrysky.OnPlayProgressListener
import com.lzx.starrysky.StarrySky
import com.lzx.starrysky.utils.showToast
import top.lyc829.mymusic.MyApp
import top.lyc829.mymusic.R
import top.lyc829.mymusic.viewmodel.EventViewModel
import java.time.LocalDate

class CircleProgressButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private var bgColor: Int
    private val progressColor: Int
    private val viewWidth: Int
    private val viewHeight: Int
    private val viewRoundWidth: Float
    private var progressValue = 0f
    private val progressMax = 100
    private val paint: Paint
    private var rectF: RectF? = null

    val eventViewModel: EventViewModel by lazy { ViewModelProvider(MyApp.context as MyApp).get(
        EventViewModel::class.java) }


    //默认处于暂停状态
    private var playOrPause: Status = Status.PAUSE
    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        //Log.d(TAG, "onDraw")
        //外层的圆
        canvas.save()
        val center = width / 2
        val radius = (center - viewRoundWidth / 2).toInt()
        paint.color = bgColor //设置背景圆环的颜色
        paint.style = Paint.Style.STROKE //设置空心
        paint.strokeWidth = viewRoundWidth //设置圆环的宽度
        paint.isAntiAlias = true //消除锯齿
        paint.isDither = true // 设置抖动
        canvas.drawCircle(center.toFloat(), center.toFloat(), radius.toFloat(), paint) //画出圆环
        canvas.save()
        //进度层的圆
        paint.color = progressColor
        paint.strokeWidth = viewRoundWidth
        rectF = RectF(
            (center - radius).toFloat(), (center - radius).toFloat(), (center
                    + radius).toFloat(), (center + radius).toFloat()
        )
        canvas.drawArc(rectF!!, -90f, 360.toFloat() * progressValue / progressMax, false, paint)

        //画播放和暂停
        val x = width
        if (playOrPause == Status.PLAY) {
            //红色 两条竖线
            paint.color = Color.RED
            paint.style = Paint.Style.FILL
            paint.strokeWidth = 3f
            canvas.drawLine(
                (3 * x / 8).toFloat(),
                (5 * x / 16).toFloat(),
                (3 * x / 8).toFloat(),
                (11 * x / 16).toFloat(),
                paint
            )
            canvas.drawLine(
                (5 * x / 8).toFloat(),
                (5 * x / 16).toFloat(),
                (5 * x / 8).toFloat(),
                (11 * x / 16).toFloat(),
                paint
            )
        } else if (playOrPause == Status.PAUSE) {
            //灰色 三角形
            val path = Path()
            paint.color = Color.DKGRAY
            paint.style = Paint.Style.STROKE
            paint.strokeWidth = 3f
            path.moveTo((7 * x / 16).toFloat(), (5 * x / 16).toFloat())
            path.lineTo((7 * x / 16).toFloat(), (11 * x / 16).toFloat())
            path.lineTo((11 * x / 16).toFloat(), (8 * x / 16).toFloat())
            path.close()
            canvas.drawPath(path, paint)
        }
        super.onDraw(canvas)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_UP) {
            if (StarrySky.with().getPlayList().isEmpty()) {
                Toast.makeText(context, "当前播放队列没有歌曲", Toast.LENGTH_SHORT).show()
                return false
            }
            if (StarrySky.with().isPlaying()) {
                StarrySky.with().pauseMusic()
            } else if (StarrySky.with().isPaused()) {
                StarrySky.with().restoreMusic()
            }
        }
        //TODO: 没有处于暂停状态，都未播放的处理
        return super.onTouchEvent(event)
    }

    private fun changePlayState() {
        if (StarrySky.with().isPlaying()) {
            playOrPause = Status.PLAY
            bgColor = Color.LTGRAY
            postInvalidate()
        } else if (StarrySky.with().isPaused()) {
            playOrPause = Status.PAUSE
            bgColor = Color.DKGRAY
            postInvalidate()
        }
    }

    //播放进度
    fun setProgressValue(progressValue: Float) {
        require(!(progressValue < 0 || progressValue > 100)) { "progressValue illegal" }
        this.progressValue = progressValue
        postInvalidate()
    }

    //设置播放状态
    fun setPlayOrPause(status: Status) {
        playOrPause = status
        if (playOrPause == Status.PAUSE) {
            bgColor = Color.DKGRAY
        } else if (playOrPause == Status.PLAY) {
            bgColor = Color.LTGRAY
        }
        postInvalidate();
        //invalidate()
    }

    //播放状态
    enum class Status {
        PLAY, PAUSE
    }

    companion object {
        private const val TAG = "CircleProgressButton"
    }

    init {
        paint = Paint()
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressButton)
        //背景环颜色
        bgColor = typedArray.getColor(R.styleable.CircleProgressButton_bgColor, Color.GRAY)
        //进度环的颜色
        progressColor =
            typedArray.getColor(R.styleable.CircleProgressButton_progressColor, Color.RED)
        //宽度和高度
        viewWidth = typedArray.getColor(R.styleable.CircleProgressButton_viewWidth, 15)
        viewHeight = typedArray.getColor(R.styleable.CircleProgressButton_viewHeight, 15)
        //外层圆环的宽度
        viewRoundWidth =
            typedArray.getColor(R.styleable.CircleProgressButton_viewRoundWidth, 4).toFloat()
        typedArray.recycle()

        observerState()
    }

    private fun observerState() {
        //观察播放状态
        eventViewModel.playBackStage.observe(context as LifecycleOwner) {
            changePlayState()
        }

        //观察播放进度
        StarrySky.with().setOnPlayProgressListener(object : OnPlayProgressListener {
            override fun onPlayProgress(currPos: Long, duration: Long) {
                setProgressValue(currPos.toFloat() * 100 / duration)
            }
        })
    }
}